package com.fr.lintcode;

import org.junit.Test;

/**
*作者：furong
*日期：2017年2月16日
*时间：下午5:17:00
*/
public class Q54 {
    /**
     * @param str: A string
     * @return An integer
     */
    public int atoi(String str) {
        str = str.trim();
        double rs = 0;
        StringBuffer sb = new StringBuffer();
        int pointCount = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c >= '0' && c <= '9') {
                sb.append(c);
            } else if (c == '.') {
                pointCount++;
                if (pointCount <= 1) {
                    sb.append(c);
                } else {
                    break;
                }
            } else if (c == '-') {
                if (i == 0) {
                    sb.append(c);
                } else {
                    break;
                }
            } else if (c == '+') {
                if (i == 0) {
                    sb.append(c);
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        try {
            rs = Double.parseDouble(sb.toString());
        } catch (Exception e) {
        }
        if (rs >= Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        } else if (rs <= Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        } else {
            return (int) rs;
        }
    }

    @Test
    public void testA() {

    }
}
